import axios from 'axios'
import { $utils } from '@helper'
import { Promise, window, document } from './ajax'
function requestHandle (params) {
  return new Promise((resolve, reject) => {
    axios(params)
      .then(res => {
        if (res && (res.unauthorized || res.statusCode === 401)) {
          window.location.href = '/login'
        }
        if (res.type === 'application/x-msdownload') {
          redirectToIframe(res.request.responseURL)
        } else if (res.status === 200 && res.data.code === '0') {
          if (res.data.success) {
            resolve(res.data.value)
          } else {
            reject(res.data.message)
          }
        }
      }, err => reject(err))
  })
}
function redirectToIframe (url) {
  let iframe = document.createElement('iframe')
  iframe.style.display = 'none'
  iframe.src = url
  iframe.onload = function () {
    document.body.removeChild(iframe)
  }
  document.body.appendChild(iframe)
}
export default {
  post: function (url, params) {
    return requestHandle({
      method: 'post',
      url: url,
      data: params
    })
  },
  get: function (url, params) {
    return requestHandle({
      method: 'get',
      url: $utils.queryString(url, params)
    })
  }
}
